package com.zhentao.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.aliyun.ChargeAliyunMsgUtils;
import com.zhentao.common.user.UserCommon;
import com.zhentao.mapper.ChargeInviteRecordMapper;
import com.zhentao.mapper.ChargeUserIncomeMapper;
import com.zhentao.mapper.ChargeUserMapper;
import com.zhentao.market.ChargeMarketFeignApi;
import com.zhentao.minio.service.impl.MinioFileStorageServiceImpl;
import com.zhentao.model.admin.vo.ChargeAdminUserVo;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.pojo.par.ChargeParOrders;
import com.zhentao.model.pojo.user.ChargeUser;
import com.zhentao.model.pojo.user.common.UserInfoCommon;
import com.zhentao.model.pojo.user.dto.UserDto;
import com.zhentao.model.pojo.user.dto.parDto;
import com.zhentao.model.pojo.user.enums.UserLoginEnum;
import com.zhentao.model.pojo.user.param.MessageParam;
import com.zhentao.model.pojo.user.param.UserParam;
import com.zhentao.model.pojo.user.record.ChargeInviteRecord;
import com.zhentao.model.pojo.user.record.ChargeUserIncome;
import com.zhentao.model.pojo.user.record.vo.InviteUserVo;
import com.zhentao.model.pojo.user.record.vo.RecordVo;
import com.zhentao.regex.RegexUtils;
import com.zhentao.service.ChargeAddBenefit;
import com.zhentao.service.ChargeParOrdersService;
import com.zhentao.service.ChargeUserLogService;
import com.zhentao.service.ChargeUserService;
import com.zhentao.user.ChargeUserThreadUtils;
import com.zhentao.user.RandomNicknameGenerator;
import com.zhentao.user.invite.InvitationCodeGenerator;
import com.zhentao.utils.JwtService;
import com.zhentao.utils.RedisIdWorker;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.zhentao.common.user.UserCommon.*;
import static com.zhentao.model.common.enums.AppHttpCodeEnum.*;

/**
 * @author lenovo
 * @description 针对表【charge_user】的数据库操作Service实现
 * @createDate 2024-12-17 09:46:37
 */
@Service
@Slf4j
public class ChargeUserServiceImpl extends ServiceImpl<ChargeUserMapper, ChargeUser>
        implements ChargeUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private ChargeInviteRecordMapper chargeInviteRecordMapper;

    @Resource
    private ChargeUserIncomeMapper chargeUserIncomeMapper;

    @Resource
    private ChargeAddBenefit benefit;

    @Autowired
    private MinioFileStorageServiceImpl fileStorageService;

    @Resource
    private ChargeUserMapper chargeUserMapper;

    /**
     * @param userDto
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description charge----user -- 登录接口
     * @author 振涛教育_小Q
     * @date 2024/12/17 9:56
     */
    @Override
    public ResponseResult login(UserDto userDto) {
        // 判断登录类型
        Integer loginType = userDto.getLoginType();
        if (loginType == null) {
            return ResponseResult.errorResult(PARAM_REQUIRE);
        }
        if (loginType == UserLoginEnum.NORMAL.getCode()) {
            log.info(UserLoginEnum.NORMAL.getMsg());
            ResponseResult result = usernameAndPsword(userDto);
            if (result == null) return ResponseResult.errorResult(PARAM_REQUIRE);
            return ResponseResult.okResult(result);
        } else if (loginType == UserLoginEnum.PHONE_CODE.getCode()) {
            log.info(UserLoginEnum.PHONE_CODE.getMsg());
            ResponseResult result = messagePhoneCodeLogin(userDto);
            if (result == null) return ResponseResult.errorResult(PARAM_REQUIRE);
            return ResponseResult.okResult(result);
        }
        return ResponseResult.okResult(SUCCESS);
    }

    /**
     * @param userDto
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 验证码手机号登录
     * @author 振涛教育_小Q
     * @date 2024/12/17 19:32
     */
    private ResponseResult messagePhoneCodeLogin(UserDto userDto) {
        // 判断参数是否有效
        if (userDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 判断手机号格式是否正确
        if (RegexUtils.isPhoneInvalid(userDto.getPhone())) {
            return ResponseResult.errorResult(CHARGE_USER_REGEX_PHONE);
        }
        // 根据手机号查询当前用户
        ChargeUser user = getOne(Wrappers.<ChargeUser>lambdaQuery()
                .eq(StringUtils.checkValNotNull(userDto.getPhone()), ChargeUser::getPhone, userDto.getPhone()));
        if (StringUtils.checkValNull(user)) {
            return ResponseResult.errorResult(CHARGE_USER_DATA_NOT_EXIST);
        }
        // 判断该用户是否被拉入黑名单
        if (user.getStatus().equals(1)) {
            return ResponseResult.errorResult(CHARGE_USER_BLACKLIST);
        }
        // 缓存获取验证码
        String code = redisTemplate.opsForValue().get(CHARGE_USER_MASSAGE_CODE_KEY);
        if (!code.equals(userDto.getCode())) {
            return ResponseResult.errorResult(CHARGE_USER_CODE_ERROR);
        }
        String token = getUserToToken(user);
        return ResponseResult.okResult(token);
    }

    /**
     * @param userDto
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 账户密码登录
     * @author 振涛教育_小Q
     * @date 2024/12/17 19:32
     */
    public ResponseResult usernameAndPsword(UserDto userDto) {
        // 判断参数是否有效
        if (userDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 判断否存在该用户
        ChargeUser user = getOne(Wrappers.<ChargeUser>lambdaQuery()
                .eq(StringUtils.checkValNotNull(userDto.getUserName()), ChargeUser::getUserName, userDto.getUserName()));
        if (StringUtils.checkValNull(user)) {
            return ResponseResult.errorResult(CHARGE_USER_DATA_NOT_EXIST);
        }
        // 判断该用户是否被拉入黑名单
        if (user.getStatus().equals(1)) {
            return ResponseResult.errorResult(CHARGE_USER_BLACKLIST);
        }
        // 校验密码是否符合规范
        if (RegexUtils.isPasswordInvalid(userDto.getPassword())) {
            return ResponseResult.errorResult(CHARGE_USER_REGEX_PASSWORD);
        }
        // 密码加密
        System.err.println(BCrypt.hashpw(userDto.getPassword()));
        // 判断密码是否正确
        if (!BCrypt.checkpw(userDto.getPassword(), user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        String token = getUserToToken(user);
        return ResponseResult.okResult(token);
    }

    /**
     * @param user
     * @return java.lang.String
     * @description 用户转换 map  --》》存储到 redis 中
     * @author 振涛教育_小Q
     * @date 2024/12/17 20:10
     */
    private String getUserToToken(ChargeUser user) {
        // 转换为map集合
        UserDto dto = new UserDto();
        BeanUtils.copyProperties(user, dto);
        dto.setPassword("");
        Map<String, Object> map = BeanUtil.beanToMap(dto, new HashMap<>()
                , CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) ->
                        {
                            // 如果 fieldValue 为 null，返回空字符串或者其他合适的默认值
                            return fieldValue != null ? fieldValue.toString() : "";
                        }));
        // 生成token
        String token = JwtService.createToken(map);
        //  存储在缓存当中将当前用户信息
        String key = UserCommon.CHARGE_USER_LOGIN_KEY + user.getId();
        redisTemplate.opsForValue().set(key, JSON.toJSONString(map));
        redisTemplate.opsForValue().set(CHARGE_USER_LOGIN_KEY_SCHEDULE, dto.getId().toString());

        // 设置过期时间
        redisTemplate.expire(key, UserCommon.CHARGE_USER_LOGIN_EXPIRE, TimeUnit.MINUTES);
        redisTemplate.expire(CHARGE_USER_LOGIN_KEY_SCHEDULE, 1, TimeUnit.DAYS);
        return token;
    }


    /**
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description charge----userInfo -- 获取当前登录用户
     * @author 振涛教育_小Q
     * @date 2024/12/17 9:56
     */
    @Override
    public ResponseResult getUserInfo() {
        ChargeUser user = ChargeUserThreadUtils.getChargeUserThreadLocal();

        if (StringUtils.checkValNull(user)) {
            return ResponseResult.errorResult(CHARGE_USER_DATA_NOT_EXIST);
        }
        // 查询当前用户根据id
        ChargeUser chargeUser = getOne(Wrappers.<ChargeUser>lambdaQuery()
                .eq(StringUtils.checkValNotNull(user.getId()), ChargeUser::getId, user.getId()));
        if (chargeUser == null) return ResponseResult.errorResult(CHARGE_USER_DATA_NOT_EXIST);
        UserDto dto = new UserDto();
        BeanUtils.copyProperties(chargeUser, dto);
        dto.setPassword("");
        return ResponseResult.okResult(dto);
    }

    /**
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description charge----messageCode -- 发送短信
     * @author 振涛教育_小Q
     * @date 2024/12/17 9:56
     */
    @Override
    public ResponseResult messageCode(MessageParam param) {
        // 判断参数是否有效
        if (param == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 创建随机数
        String code = RandomUtil.randomNumbers(6);
        // 存储在缓存当中
        redisTemplate.opsForValue().set(CHARGE_USER_MASSAGE_CODE_KEY, code);
        redisTemplate.expire(CHARGE_USER_MASSAGE_CODE_KEY, CHARGE_USER_MASSAGE_CODE_EXPIRE, TimeUnit.SECONDS);
        param.setCode(code);
        param.setExpireTime(5L);
        ChargeAliyunMsgUtils.sendMsg(param.getPhone(), Integer.valueOf(param.getCode()), param.getExpireTime());
        return ResponseResult.okResult(SUCCESS);
    }


    /**
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description charge----registry -- 用户注册
     * @author 振涛教育_小Q
     * @date 2024/12/17 9:56
     */
    @Override
    @Transactional  // spring事务管理
    public ResponseResult chargeRegistry(UserParam param) {
        // 判断参数是否有效
        ResponseResult result = regexUserInfo(param);
        if (!result.getCode().equals(200)) {
            return ResponseResult.errorResult(400, result.getErrorMessage());
        }
        // 创建用户
        ChargeUser user = new ChargeUser();
        // 昵称随机生成
        user.setNickName(RandomNicknameGenerator.generateNickname());
        // 账户
        user.setUserName(param.getUserName());
        // 密码加密
        String bcryptPassword = BCrypt.hashpw(param.getPassword());
        user.setPassword(bcryptPassword);
        // 手机号
        user.setPhone(param.getPhone());
        // 电子邮箱
        user.setEmail(param.getEmail());
        user.setType(UserInfoCommon.USER_TYPE);
        user.setAuthentication(UserInfoCommon.AUTHENTICATION);
        user.setVip(UserInfoCommon.USER_VIP);
        user.setBalance(BigDecimal.ZERO);  // 默认可用余额为 0
        user.setPoint(UserInfoCommon.USER_POINT);  // 新用户注册可用积分为 100
        // 新用户默认生成随机 邀请码
        String inviteCodeText = InvitationCodeGenerator.generateInvitationCode(param.getPhone());
        user.setInviteCode(inviteCodeText);
        user.setStatus(UserInfoCommon.USER_STATUS);
        user.setCreateTime(new Date());
        boolean save = save(user);

        // 判断是否拥有邀请注册码
        ChargeUser chargeUser = null;
        // 判断邀请码是否真实存在
        if (StringUtils.checkValNotNull(param.getInvitedCode())) {
            // 如果有邀请码，那么就查询该邀请码是否真实存在
            chargeUser = getOne(Wrappers.<ChargeUser>lambdaQuery()
                    .eq(StringUtils.checkValNotNull(param.getInvitedCode()), ChargeUser::getInviteCode, param.getInvitedCode()));
            if (chargeUser == null) {
                return ResponseResult.errorResult(400001, "邀请码不存在");
            }
            // 邀请码存在，那么对拥有该邀请码的用户进行增加福利 -- 异步处理  福利增加
            benefit.addBenefit(user.getId(), chargeUser);
        }
        return save ? ResponseResult.okResult(SUCCESS) : ResponseResult.errorResult(SERVER_ERROR);
    }


    /**
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description charge----updateUserInfo -- 编辑当前用户的基本信息
     * @author 振涛教育_小Q
     * @date 2024/12/22 10:38
     */
    @Override
    public ResponseResult updateUserInfo(UserParam param) {
        boolean flag = false;
        // 判断参数是否有效
        if (param == null) {
            return ResponseResult.errorResult(PARAM_REQUIRE);
        }
        // 查询当前昵称是否已经被使用
        ChargeUser user = getOne(Wrappers.<ChargeUser>lambdaQuery()
                .eq(StringUtils.checkValNotNull(param.getNickName()), ChargeUser::getNickName
                        , param.getNickName()));
        if (!param.getId().equals(user.getId()) && param.getNickName().equals(user.getNickName()))
            return ResponseResult.errorResult(400, "该昵称已被使用");
        // 头像处理 从redis中获取
        String imgPath = redisTemplate.opsForValue().get(CHARGE_USER_REDIS_PREFIX_AVATAR_IMG);
        if (imgPath == null) {
            // 如果图片为空说明没有对头像进行修改 -- > 修改用户基本信息
            ChargeUser user1 = new ChargeUser();
            user1.setId(param.getId());
            user1.setNickName(param.getNickName());
            flag = updateById(user1);
            return flag ? ResponseResult.okResult(SUCCESS) : ResponseResult.errorResult(400, "修改失败");
        }
        // 修改用户基本信息 -- > 否则全部修改
        ChargeUser user1 = new ChargeUser();
        user1.setId(param.getId());
        user1.setNickName(param.getNickName());
        user1.setAvatarImg(imgPath);
        flag = updateById(user1);
        return flag ? ResponseResult.okResult(SUCCESS) : ResponseResult.errorResult(400, "修改失败");
    }

    /**
     * @param
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 退出登录
     * @author 振涛教育_小Q
     * @date 2024/12/22 13:04
     */
    @Override
    public ResponseResult userLogout() {
        ChargeUser user = ChargeUserThreadUtils.getChargeUserThreadLocal();
        // 清空缓存中的用户
        Boolean delete = redisTemplate.delete(CHARGE_USER_LOGIN_KEY + user.getId());
        return delete ? ResponseResult.okResult(200000, "登出成功") : ResponseResult.errorResult(400, "登出失败");
    }

    /**
     * @param
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 获取当前用户的可用积分
     * @author 振涛教育_小Q
     * @date 2024/12/22 20:29
     */
    @Override
    public ResponseResult getUserPoint(Long id) {
        if (id == null) {
            return ResponseResult.errorResult(SERVER_ERROR);
        }
        // 根据当前登录用户id查询可用积分
        ChargeUser chargeUser = getById(id);
        return ResponseResult.okResult(chargeUser);
    }

    /**
     * @param point
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 扣减库存
     * @author 振涛教育_小Q
     * @date 2024/12/26 16:38
     */
    @Override
    public ResponseResult getDeductionCount(Integer point, Long userId) {
        if (point == null) {
            return ResponseResult.errorResult(PARAM_REQUIRE);
        }
        ChargeUser chargeUser = getById(userId);
        if (chargeUser.getPoint() < point) {
            // 积分不足
            return ResponseResult.errorResult(501, "积分不足");
        }
        // 可以扣减
        chargeUser.setPoint(chargeUser.getPoint() - point);
        boolean bool = updateById(chargeUser);
        return bool ? ResponseResult.okResult(SUCCESS) : ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    @Override
    public ResponseResult GetPurseMoney() {
        ChargeUser chargeUserThreadLocal = ChargeUserThreadUtils.getChargeUserThreadLocal();

        ChargeUser byId = this.getById(chargeUserThreadLocal.getId());
        if (byId == null) {
            return ResponseResult.errorResult(400, "用户不存在");
        }

        byId.setPassword("");
        byId.setUserName("");

        return ResponseResult.okResult(byId);
    }

    @Resource
    ChargeParOrdersService chargeParOrdersService;

    @Resource
    RedisIdWorker redisIdWorker;
    @Resource
    private ChargeMarketFeignApi marketFeignApi;

    @SneakyThrows
    public ResponseResult uploadImg(MultipartFile file) {
        if (file != null) {
            String path = fileStorageService.uploadImgFile(UserCommon.CHARGE_USER_REDIS_PREFIX_AVATAR_IMG, file.getOriginalFilename(), file.getInputStream());
            redisTemplate.opsForValue().set(CHARGE_USER_REDIS_PREFIX_AVATAR_IMG, path);
            return ResponseResult.okResult(path);
        }
        return ResponseResult.errorResult(400, "上传失败");
    }

    @Resource
    private ChargeUserLogService logService;

    /**
     * <<<<<<< HEAD
     *
     * @param
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 统计用户数量  和  用户的活跃度
     * @author 振涛教育_小Q
     * @date 2024/12/31 16:10
     */
    @Override
    public ResponseResult getUserCount() {
        // 用户数量
        long count = list().size();
        ChargeAdminUserVo vo = new ChargeAdminUserVo();
        vo.setRegistryUserCount(count);
        // 获取在当前月份的用户信息
        long activeCount = logService.list().size();
        vo.setActiveUserCount(activeCount);
        return ResponseResult.okResult(vo);
    }

    /*
     * @description 获取用户列表
     * @author W177
     * @return
     */
    @Override
    public List<ChargeUser> getUserList() {
        List<ChargeUser> chargeUsers = chargeUserMapper.selectList(null);
        return chargeUsers;
    }

    @Override
    public ResponseResult addBlackList(Integer userId) {
        // 判断参数
        if (userId == null) {
            return ResponseResult.errorResult(400, "参数错误");
        }
        ChargeUser one = chargeUserMapper.selectOne(Wrappers.<ChargeUser>lambdaQuery().eq(ChargeUser::getId, userId));
        one.setStatus(1);
        boolean update = updateById(one);
        return ResponseResult.okResult("加入成功");
    }

    @Override
    public ChargeUser getUser(Long id) {
        ChargeUser one = chargeUserMapper.selectOne(Wrappers.<ChargeUser>lambdaQuery().eq(ChargeUser::getId, id));
        return one;
    }


    /**
     * 支付生成订单
     *
     * @param
     * @return
     */
    @Override
    public ResponseResult Remittance(parDto pardto) {

        if (pardto == null) {
            return ResponseResult.errorResult(PARAM_REQUIRE);
        }
        ChargeUser chargeUserThreadLocal = ChargeUserThreadUtils.getChargeUserThreadLocal();
        ChargeUser byId = this.getById(chargeUserThreadLocal.getId());
        if (byId.getBalance().doubleValue() < pardto.getAmount()) {
            return ResponseResult.errorResult(400, "余额不足");
        }
        if (pardto.getAmount() == 0 && byId.getBalance().doubleValue() < pardto.getActualPrice()) {
            return ResponseResult.errorResult(400, "余额不足");
        }


        if (byId.getBalance().doubleValue() >= pardto.getAmount()) {
            double v = byId.getBalance().doubleValue() - pardto.getAmount();
            BigDecimal amountBD = new BigDecimal(v).setScale(2, RoundingMode.HALF_UP);
            byId.setBalance(amountBD);
            boolean b = this.updateById(byId);
            if (b) {
                // 修改优惠券状态
                List<Integer> userCouponIdList1 = pardto.getUserCouponIdList();
                marketFeignApi.updateByIdCouponStatus(userCouponIdList1);

                ChargeParOrders chargeParOrders = new ChargeParOrders();
                chargeParOrders.setUserId(chargeUserThreadLocal.getId().intValue());
                chargeParOrders.setNickName(byId.getNickName());
                chargeParOrders.setActualPrice(pardto.getActualPrice());
                chargeParOrders.setAmout(pardto.getAmount());
                chargeParOrders.setChargeStationInfoId(pardto.getChargeRecordId());
                chargeParOrders.setVehicleIdentifyNo(pardto.getVehicleIdentifyNo());
                List<Integer> userCouponIdList = pardto.getUserCouponIdList();
                String s = JSON.toJSONString(userCouponIdList);
                long par = redisIdWorker.nextId("par");
                chargeParOrders.setMarketId(s);
                chargeParOrders.setId(par);
                chargeParOrders.setVehicleIdentifyNo(pardto.getVehicleIdentifyNo());
                boolean save = chargeParOrdersService.save(chargeParOrders);
                if (save) {
                    return ResponseResult.okResult(SUCCESS);
                }
            }
        }

        if (byId.getBalance().doubleValue() >= pardto.getActualPrice()) {
            double v = byId.getBalance().doubleValue() - pardto.getActualPrice();
            BigDecimal amountBD = new BigDecimal(v).setScale(2, RoundingMode.HALF_UP);
            byId.setBalance(amountBD);
            boolean b = this.updateById(byId);
            if (b) {

                // 修改优惠券状态
                List<Integer> userCouponIdList1 = pardto.getUserCouponIdList();
                marketFeignApi.updateByIdCouponStatus(userCouponIdList1);


                ChargeParOrders chargeParOrders = new ChargeParOrders();
                chargeParOrders.setUserId(chargeUserThreadLocal.getId().intValue());
                chargeParOrders.setNickName(byId.getNickName());
                chargeParOrders.setActualPrice(pardto.getActualPrice());
                chargeParOrders.setAmout(pardto.getAmount());
                chargeParOrders.setChargeStationInfoId(pardto.getChargeRecordId());
                List<Integer> userCouponIdList = pardto.getUserCouponIdList();
                String s = JSON.toJSONString(userCouponIdList);
                long par = redisIdWorker.nextId("par");
                chargeParOrders.setMarketId(s);
                chargeParOrders.setId(par);
                boolean save = chargeParOrdersService.save(chargeParOrders);
                if (save) {
                    return ResponseResult.okResult(SUCCESS);
                }
            }
        }

        return ResponseResult.errorResult(400, "支付失败");
    }

    /**
     * @param param
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @description 用户注册 ---》》参数校验
     * @author 振涛教育_小Q
     * @date 2024/12/18 13:55
     */
    public ResponseResult regexUserInfo(UserParam param) {
        if (param == null) {
            return ResponseResult.errorResult(PARAM_REQUIRE);
        }
        // 校验用户名是否已被使用
        ChargeUser user = getOne(Wrappers.<ChargeUser>lambdaQuery()
                .eq(StringUtils.checkValNotNull(param.getUserName()), ChargeUser::getUserName, param.getUserName()));
        if (user != null) return ResponseResult.errorResult(400, "该用户名已被使用");
        // 校验手机号是否符合规则
        if (RegexUtils.isPhoneInvalid(param.getPhone()))
            return ResponseResult.errorResult(CHARGE_USER_REGEX_PHONE);

        ChargeUser user1 = getOne(Wrappers.<ChargeUser>lambdaQuery()
                .eq(StringUtils.checkValNotNull(param.getPhone()), ChargeUser::getPhone, param.getPhone()));

        // 校验该手机号是否被使用
        if (user1 != null) {
            return ResponseResult.errorResult(400, "该手机号已经注册过");
        }

        // 校验密码是否符合规则
        if (RegexUtils.isPasswordInvalid(param.getPassword()))
            return ResponseResult.errorResult(CHARGE_USER_REGEX_PASSWORD);
        // 校验邮箱是否符合规则
        if (RegexUtils.isEmailInvalid(param.getEmail()))
            return ResponseResult.errorResult(CHARGE_USER_REGEX_EMAIL);
        return ResponseResult.okResult(200, "信息校验成功");
    }

    /**
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @author W177
     * @date 2024/12/17 14:06
     */
    @Override
    public ResponseResult getInviteRecord() {
        //获取当前登录人
        ChargeUser user = ChargeUserThreadUtils.getChargeUserThreadLocal();
        //判断当前登陆人
        if (user == null) {
            return ResponseResult.errorResult(CHARGE_USER_DATA_NOT_EXIST);
        }
        //获取当前登录人的邀请人列表
        List<ChargeInviteRecord> records = chargeInviteRecordMapper.selectList(
                Wrappers.<ChargeInviteRecord>lambdaQuery().eq(ChargeInviteRecord::getInviteUserId, user.getId()));
        // 邀请人个数
        int count = records.size();
        // 获取被邀请人的id
        for (int i = 0; i < records.size(); i++) {
            ChargeInviteRecord inviteRecord = records.get(i);
            InviteUserVo userVo = new InviteUserVo();
            userVo.setInvitedTime(inviteRecord.getInvitedTime());
            // 被邀请人id
            Long invitedUserId = inviteRecord.getInvitedUserId();
            // 根据被邀请人id查询对应的信息
            if (invitedUserId != null) {
                ChargeUser chargeUser = getOne(Wrappers.<ChargeUser>lambdaQuery()
                        .eq(StringUtils.checkValNotNull(invitedUserId), ChargeUser::getId,
                                invitedUserId));
                if (chargeUser != null) {
                    userVo.setNickName(chargeUser.getNickName());
                }
            }
            records.set(i, userVo);
        }
        return ResponseResult.okResult(records);
    }


    /**
     * @return com.zhentao.model.common.dtos.ResponseResult
     * @author W177
     * @date 2024/12/17 14:06
     */
    @Override
    public ResponseResult getInviteIncome() {
        //获取当前用户
        ChargeUser user = ChargeUserThreadUtils.getChargeUserThreadLocal();
        if (user == null) {
            return ResponseResult.errorResult(CHARGE_USER_DATA_NOT_EXIST);
        }
        //根据当前用户
        List<ChargeUserIncome> incomes = chargeUserIncomeMapper.selectList(Wrappers.<ChargeUserIncome>lambdaQuery().eq(ChargeUserIncome::getUserId, user.getId()));
        // 初始化余额数

        RecordVo recordVo = new RecordVo();
        // 循环遍历
        for (int i = 0; i < incomes.size(); i++) {
            ChargeUserIncome incomeUser = incomes.get(i);
            // 添加收益
            recordVo.setIncome(recordVo.getIncome().add(incomeUser.getIncome()));
            // 添加在途收益  如果 在途为 0 那么就以0展示
            if (Objects.equals(incomeUser.getTransit(), BigDecimal.valueOf(0))) {
                recordVo.setInvitingIncome(BigDecimal.valueOf(0));
            } else {
                // 否则添加在途收益
                recordVo.setInvitingIncome(recordVo.getInvitingIncome().add(incomeUser.getTransit()));
            }
            incomes.set(i, recordVo);
        }

        return ResponseResult.okResult(recordVo);
    }


}





